package com.s53.crm.clue.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.s53.crm.clue.service.IUserService;
import com.s53.crm.entity.Common;
import com.s53.crm.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-04-20
 */
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
@RefreshScope
public class UserController {
    @Value("${server.port}")
    private int port;

    @Value("${email}")
    private String email;

    @Value("${subject}")
    private String subject;

    private final IUserService userService;

    @PostMapping("/list")
    @SentinelResource(value = "userList", blockHandler = "handlerBlock")
    public Common list(@RequestBody User user,
                       @RequestParam("current") int current,
                       @RequestParam("size") int size) {
        System.out.println(port + "-" + email + "-" + subject);
        LambdaQueryWrapper<User> queryWrapper
                = Wrappers.lambdaQuery(User.class).like(StringUtils.hasText(user.getUsername()), User::getUsername, user.getUsername());
        return Common.success(userService.page(Page.of(current, size), queryWrapper));
    }

    public Common handlerBlock(User user, int current, int size, BlockException ex) {
        return Common.error(503, "限流了");
    }
}
